#include <iostream>
#include <cstdio>
#include <unistd.h>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

//    ./udp_client desc_ip desc_port
void Usage(std::string proc)
{
  std::cerr << "Usage: " << "\n\t" << proc << "desc_ip desc_port" << std::endl;
}

int main(int argc, char *argv[])
{
  if(argc != 3)
  {
    Usage(argv[0]);
    return 1;
  }

  int sock = socket(AF_INET, SOCK_DGRAM, 0);
  if(sock < 0)
  {
    std::cerr << "socket error" << std::endl;
    return 1;
  }
  
  char buffer[1024];

  struct sockaddr_in desc;
  memset(&desc, 0, sizeof(desc));
  desc.sin_family = AF_INET;
  desc.sin_port = htons(atoi(argv[2]));   //先将字符串端口号转成整型，再主机转网络
  desc.sin_addr.s_addr = inet_addr(argv[1]);    //将字符串点分十进制ip转为二进制
  
  for( ; ; )
  {
    std::cout << "Please Enter# ";
    fflush(stdout);
    buffer[0] = 0;
    ssize_t size = read(0, buffer, sizeof(buffer) - 1);
    if(size > 0)
    {
      buffer[size - 1] = 0;
      //std::cout << "echo# " << buffer << std::endl;
      sendto(sock, buffer, strlen(buffer), 0, (struct sockaddr*)&desc, sizeof(desc));
      
      //服务端将接收到的客户端消息传送回来
      struct sockaddr_in peer;
      socklen_t len = sizeof(peer);
      ssize_t s = recvfrom(sock, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&peer, &len);
      if(s > 0)
      {
        buffer[s] = 0;
        std::cout << "echo#" << buffer << std::endl;
      }
    }
  }

  close(sock);
  return 0;
}
